// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/caching/scan_tracker.h>
#include <pollux/common/caching/file_group_stats.h>

#include <sstream>

namespace kumo::pollux::cache {
    // Marks that 'bytes' worth of data may be accessed in the future. See
    // TrackingData for meaning of quantum.
    void ScanTracker::recordReference(
        const TrackingId id,
        uint64_t bytes,
        uint64_t fileId,
        uint64_t groupId) {
        if (fileGroupStats_) {
            fileGroupStats_->recordReference(fileId, groupId, id, bytes);
        }
        std::lock_guard<std::mutex> l(mutex_);
        auto &data = data_[id];
        data.referencedBytes += bytes;
        data.lastReferencedBytes = bytes;
        sum_.referencedBytes += bytes;
    }

    void ScanTracker::recordRead(
        const TrackingId id,
        uint64_t bytes,
        uint64_t fileId,
        uint64_t groupId) {
        if (fileGroupStats_) {
            fileGroupStats_->recordRead(fileId, groupId, id, bytes);
        }
        std::lock_guard<std::mutex> l(mutex_);
        auto &data = data_[id];
        data.readBytes += bytes;
        sum_.readBytes += bytes;
    }

    std::string ScanTracker::toString() const {
        std::stringstream out;
        out << "ScanTracker for " << id_ << std::endl;
        for (const auto &[id, data]: data_) {
            out << id.id() << ": " << data.readBytes << "/" << data.referencedBytes
                    << std::endl;
        }
        return out.str();
    }
} // namespace kumo::pollux::cache
